<template>
  <x-drawer :visible.sync="shareVisible" background="none" @cancel="closeShareVisible">
    <view class="p-drawer">
      <view class="_header">
        <text class="_title">分享</text>
        <view class="icon" @click="closeShareVisible">
          <x-icon name="icon-025" size="28" color="#C8C9CC"></x-icon>
        </view>
      </view>
      <view class="_share">
        <view class="_item">
          <x-button openType="share" transparent styles="background:#ffffff;border:none;display: flex;flex-direction: column;justify-content: center;align-items: center;">
            <view class="_img">
              <x-icon name="icon-030" size="54" color="#FFFFFF"/>
            </view>
            <view class="_text">分享给好友</view>
          </x-button>
        </view>
        <view class="_item" @click="getImageInfo_local">
          <view class="_img" style="background: #FAAB0C">
            <x-icon name="icon-043" size="54" color="#FFFFFF"/>
          </view>
          <view class="_text">生成海报</view>
        </view>
      </view>
      <view class="_cancel" @click="closeShareVisible">
        <text class="_title">取消</text>
      </view>
    </view>

    <view class="_canvas">
      <canvas type="2d" canvas-id="mycanvas" id="mycanvas" style="width: 750rpx; height: 1048rpx;" />
    </view>
  </x-drawer>
</template>

<script>
import XDrawer from '@/components/x-drawer';
import XIcon from '@/components/x-icon';
import XButton from '@/components/x-button';

export default {
  name: 'PDrawerShare',
  components: {
    XButton,
    XDrawer,
    XIcon
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    from: {
      type: String,
      default: 'detail'
    },
    detail: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      shareVisible: this.visible,
      // productInfo: {
      //   productTitle: '阿斯利康等会拉康师傅里肯定能拉丝带回来',
      //   productMainPic: 'https://alicdn.itaored.com/test/feima-uploaded/images/86/dd/86dd82ef11c7684128815653002c6e06.jpg',
      //   sellingPrice: '19.00',
      //   originalPrice: '29.00'
      // },
      productInfo: this.detail,
      wx_mini_qrcode_goods: 'https://alicdn.itaored.com/test/feima-uploaded/images/86/dd/86dd82ef11c7684128815653002c6e06.jpg',
      posterImage: ''
    };
  },
  mounted() {

  },
  watch: {
    detail(val) {
      console.log(val);
      this.productInfo = val;
    }
  },
  async created() {
    await this.getWxMiniQrcode();
  },
  computed: {},
  methods: {
    closeShareVisible() {
      this.shareVisible = false;
      this.$emit('update:visible', false);
    },
    //  生成分享海报
    createNewImg: function() {
      uni.showLoading({
        title: '海报生成中！',
        mask: true
      });
      setTimeout(() => {
        uni.hideLoading();
      }, 5000);
      let canvas = '';
      const query = uni.createSelectorQuery().in(this);
      query.select('#mycanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res && res[0] && res[0].node) {
            canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            const dpr = uni.getWindowInfo().pixelRatio;
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);
            this.canvasWidth = res[0].width;
            this.canvasHeight = res[0].height;
            this.canvasRatio = res[0].width / 750;
            // 绘制画布矩形背景
            this.canvasBg(ctx);
            this.drawShopImg(canvas, ctx);
          }
        });
    },
    getImageInfo_local: function() { // 获取网络图片到本地地址
      const that = this;
      this.posterVisible = true;
      uni.getImageInfo({
        src: that.productInfo.productMainPic, // 服务器返回的图片地址
        success: function(res) {
          // res.path是网络图片的本地地址
          console.log(res);
          that.share_img_width = res.width;
          that.share_img_height = res.height;
          that.createNewImg();
        },
        fail: function(res) {
          // 失败回调
          console.log(res);
        }
      });
    },
    // 绘制图片缩略图
    drawShopImg(canvas, ctx) {
      console.log('绘制图片缩略图');
      const that = this;
      const img = canvas.createImage();
      img.src = this.productInfo.productMainPic;
      img.onload = () => {
        // ctx.drawImage(img, 0, 40, this.canvasWidth, this.canvasWidth * (this.share_img_height / this.share_img_width));
        ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasWidth);
        ctx.restore();
        that.drawErCode(canvas, ctx);
      };
    },
    // 获取二维码地址
    async getWxMiniQrcode() {
      const params = {
        type: 1,
        path: this.from === 'detail' ? `pages/goods-detail/index?id=${this.productInfo.id}` : `pages/advertising/index?id=${this.productInfo.pageId}` // 小程序路径
        // path: 'pages/index/index' // 小程序路径
      };
      this.$http({
        login: true,
        url: '/account/store/qrcode/img',
        method: 'post',
        report: true,
        // responseType: 'arraybuffer',
        data: params
      }).then(res => {
        // console.log(res);
        this.wx_mini_qrcode_goods = res.data;
      }).catch(() => {

      });
    },
    // 绘制二维码图
    drawErCode(canvas, ctx) {
      console.log('绘制二维码');
      const that = this;
      // const wx_mini_qrcode_goods = 'data:image/png;base64,' + wx.arrayBufferToBase64(this.wx_mini_qrcode_goods);
      const wx_mini_qrcode_goods = this.wx_mini_qrcode_goods;
      // console.log(that.wx_mini_qrcode_goods);
      // mock 二维码地址
      // const wx_mini_qrcode_goods = 'https://alicdn.itaored.com/test/feima-uploaded/images/b7/03/b7030eee925edab07f2e9c6639cebd35.jpeg';
      if (wx_mini_qrcode_goods) {
        const img = canvas.createImage();
        img.src = wx_mini_qrcode_goods;
        img.onload = () => {
          // console.log(img.complete)
          ctx.drawImage(img, that.canvasWidth - 216 * this.canvasRatio, that.canvasWidth + 42 * this.canvasRatio, 160 * this.canvasRatio, 160 * this.canvasRatio);
          ctx.restore();
          // 绘制价格
          this.canvasPrice(ctx);
          // 绘制标题
          this.canvasTitle(ctx);
          // //绘制右下角扫码提示语
          ctx.font = '14px PingFang SC';
          ctx.fillStyle = '#999999';
          ctx.textAlign = 'left';
          ctx.fillText('扫描或长按二维码', that.canvasWidth - 248 * this.canvasRatio, that.canvasWidth + 250 * this.canvasRatio, 224 * this.canvasRatio, 25);
          // canvas转图片
          uni.canvasToTempFilePath({
            canvas: canvas,
            success: function(res) {
              uni.hideLoading();
              // const tempFilePath = res.tempFilePath;
              that.posterImage = res.tempFilePath;
              uni.hideToast();
              that.posterLoad = true;
              that.$emit('shareImage', { posterImage: that.posterImage });
            },
            fail: function(err) {
              uni.showLoading({
                icon: 'none',
                title: '海报生成失败！',
                mask: true
              });
              console.warn(err);
              setTimeout(() => {
                uni.hideLoading();
              }, 1000);
            }
          });
        };
        img.onerror = () => {
          uni.showLoading({
            icon: 'none',
            title: '海报生成失败！',
            mask: true
          });
          setTimeout(() => {
            uni.hideLoading();
          }, 1000);
        };
      } else {
        uni.showLoading({
          icon: 'none',
          title: '海报生成失败！',
          mask: true
        });
        setTimeout(() => {
          uni.hideLoading();
        }, 1000);
      }
    },
    canvasBg(ctx) {
      console.log('生成背景');
      ctx.fillStyle = '#ffffff';
      ctx.strokeStyle = 'transparent';
      const x = 0;
      const r = 10;
      const y = 0;
      const h = this.canvasHeight;
      const w = this.canvasWidth;
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
      // border-top
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
      // border-right
      ctx.lineTo(x + w, y + h - r);
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
      // border-bottom
      ctx.lineTo(x + r, y + h);
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
      // border-left
      ctx.lineTo(x, y + r);
      ctx.lineTo(x + r, y);
      // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
      ctx.fill();
      ctx.closePath();
      // 剪切
      ctx.clip();
    },
    //  绘制商品标题
    canvasTitle(ctx) {
      const that = this;
      const productTitle = that.productInfo.productTitle;
      ctx.font = '18px PingFang SC';
      ctx.fillStyle = '#323233';
      ctx.textAlign = 'left';
      const chr = productTitle.split('');// 这个方法是将一个字符串分割成字符串数组
      let temp = '';
      let row = [];
      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < (this.canvasWidth * 440 / 750)) {
          temp += chr[a];
        } else {
          a--; // 这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = '';
        }
      }
      row.push(temp);
      // 如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        const rowCut = row.slice(0, 2);
        const rowPart = rowCut[1];
        let test = '';
        const empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < this.canvasWidth) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        const group = empty[0].slice(0, empty[0].length - 3) + '...';// 这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], 16, that.canvasWidth + 36 + b * 26);
      }
    },
    //  绘制商品价格
    canvasPrice(ctx) {
      const that = this;
      const tips = '¥';
      const subsidyAmount = that.productInfo.subsidyAmount || 0; // 补贴价
      // console.log(that.productInfo);
      let newPrice = '';
      if (that.productInfo.productSafeguard) {
        newPrice = that.productInfo.productSafeguard.groupMode === 1 ? that.productInfo.groupPrice : that.productInfo.purchasePrice;
      } else {
        newPrice = that.productInfo.sellingPrice;
      }
      const price = this.$tools.formatZero(newPrice - subsidyAmount); // 售价-补贴价
      const originalPrice = '¥' + this.$tools.formatZero(that.productInfo.originalPrice); // 原价
      ctx.font = 'bold 12px PingFang SC';
      ctx.fillStyle = '#EB441F';
      ctx.textAlign = 'left';
      const tipsWidth = ctx.measureText(tips).width;
      ctx.fillText('¥', 16, that.canvasWidth + 252 * this.canvasRatio);
      ctx.stroke();
      ctx.font = 'bold 26px PingFang SC';
      ctx.fillStyle = '#EB441F';
      ctx.textAlign = 'left';
      const priceWidth = ctx.measureText(price).width;
      ctx.fillText(price, 16 + tipsWidth, that.canvasWidth + 252 * this.canvasRatio);
      ctx.stroke();
      // 绘制价格划线见面
      // let textWidth = ctx.measureText(originalPrice).width;
      let textWidth = ctx.measureText(originalPrice).width * this.canvasRatio + 5;
      // console.log(originalPrice, textWidth);
      if (that.productInfo.originalPrice) {
        ctx.font = '15px PingFang SC';
        ctx.fillStyle = '#999999';
        ctx.textAlign = 'left';
        ctx.fillText(originalPrice, priceWidth + tipsWidth + 22, that.canvasWidth + 252 * this.canvasRatio);
        ctx.stroke();
      } else {
        textWidth = 0;
      }

      // console.log(textWidth)
      ctx.beginPath();
      ctx.rect(priceWidth + tipsWidth + 22, that.canvasWidth + 244 * this.canvasRatio, textWidth, 1);
      ctx.fillStyle = '#999999';
      ctx.fill();
    }
  }
};
</script>

<style lang="scss">
.p-drawer {
  background: #FFFFFF;
  border-radius: 20px 20px 0px 0px;
  padding-bottom: env(safe-area-inset-bottom);

  ._header {
    text-align: center;
    padding: 36px 40px;
    border-bottom: 1px solid $uni-border-color1;
    ._title {
      font-size: 32px;
      color: #323233;
      padding-left: 80px;
    }
    .icon {
      width: 80px;
      height: 80px;
      text-align: right;
      float: right;
    }
  }
  ._share {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 32px 0;
    width: 100%;
    ._item {
      width: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      ._img {
        width: 96px;
        height: 96px;
        border-radius: 50%;
        background: #07C160;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      ._text {
        color: #323233;
        font-size: 28px;
        margin-top: 16px;
      }
    }
  }

  ._cancel {
    text-align: center;
    padding: 36px 40px;
    border-top: 1px solid $uni-border-color1;

    ._title {
      font-size: 32px;
      color: #323233;
    }
  }
}

._canvas{ position: absolute; overflow: hidden; top: -999999px; left: -999999px; z-index: 0;}
</style>
